<?php
/******************************
 * EQdkp
 * Copyright 2002-2003
 * Licensed under the GNU GPL.  See COPYING for full terms.
 * ------------------
 * additem.php
 * Began: Fri December 27 2002
 *
 * $Id: additem.php 541 2008-05-20 06:56:16Z rspeicher $
 *
 ******************************/

define('EQDKP_INC', true);
define('IN_ADMIN', true);
$eqdkp_root_path = './../';
include_once($eqdkp_root_path . 'common.php');

$fv = new Form_Validate;

// Obtain var settings
$item_id = ( !empty($_REQUEST[URI_ITEM]) ) ? intval($_REQUEST[URI_ITEM]) : '';
$confirm = ( !empty($_POST['confirm']) ) ? true : false;

// Start session management
$user->start();
$user->setup();

// Delete confirmation
// If they didn't confirm, redirect them to the last page they were on
if ( isset($_POST['cancel']) )
{
    if ( $item_id )
    {
        $redirect = 'additem.php'.$SID.'&' . URI_ITEM . '='.$item_id;
    }
    else
    {
        $redirect = 'additem.php'.$SID;
    }

    redirect($redirect);
}

// Figure out what submit button was pressed
$add    = ( isset($_POST['add']) ) ? true : false;
$update = ( isset($_POST['update']) ) ? true : false;
$delete = ( isset($_POST['delete']) ) ? true : false;

// Figure out action based on submit
if ( $add )
{
    $user->check_auth('a_item_add');
    $action = 'add';
}
elseif ( $update )
{
    $user->check_auth('a_item_upd');
    $action = 'update';
}
elseif ( ($delete) || ($confirm) )
{
    $user->check_auth('a_item_del');
    $action = 'delete';
}
else
{
    $user->check_auth('a_item_');
    $action = 'display';
}

//
// Error Checking and variable initialization
//
if ( ($add) || ($update) || ($delete) )
{
    $_POST = htmlspecialchars_array($_POST);
    
    $item_added_by = $user->data['username'];
    $item_updated_by = $user->data['username'];

    if ( (!isset($_POST['item_buyers'])) || (!is_array($_POST['item_buyers'])) )
    {
        $fv->errors['item_buyers'] = $user->lang['fv_required_buyers'];
    }
    $fv->is_number('item_value', $user->lang['fv_number_value']);
    $fv->is_filled(array(
        'raid_id' => $user->lang['fv_required_raidid'],
        'item_value' => $user->lang['fv_required_value'])
    );

    if ( !empty($_POST['item_name']) )
     {
      $item_name = $_POST['item_name'];
     }
    elseif ( !empty($_POST['select_item_name']) )
     {
      $item_name = $_POST['select_item_name'];
     }
    else
     {
      $fv->errors['item_name'] = $user->lang['fv_required_item_name'];
     }

    // If there's errors, negate the whole thing since we'll need to re-display the form
    if ( $fv->is_error() )
    {
        $action = 'display';
    }
}

//
// Get relevant data
//
if ( $item_id )
{
    $sql = 'SELECT item_name, item_buyer, raid_id, item_value, item_date, item_group_key
            FROM ' . ITEMS_TABLE . "
            WHERE item_id='".$item_id."'";
    $result = $db->query($sql);
    if ( !$row = $db->fetch_record($result) )
    {
        message_die($user->lang['error_invalid_item_provided']);
    }
    $db->free_result($result);

    $item_date = $row['item_date'];
    $item = array(
        'select_item_name' => post_or_db('select_item_name', false),
        'item_name' => post_or_db('item_name', true, $row),
        'raid_id' => post_or_db('raid_id', true, $row),
        'item_value' => post_or_db('item_value', true, $row)
    );

    $sql = 'SELECT item_buyer
            FROM ' . ITEMS_TABLE . "
            WHERE item_group_key='".$row['item_group_key']."'";
    $result = $db->query($sql);
    while ( $brow = $db->fetch_record($result) )
    {
        $buyers[] = $brow['item_buyer'];
    }
    $item['item_buyers'] = ( !empty($_POST['item_buyers']) ) ? $_POST['item_buyers'] : $buyers;
    unset($buyers);
}
else
{
    $item_date = time();
    $item = array(
        'select_item_name' => post_or_db('select_item_name', false),
        'item_name' => post_or_db('item_name', false),
        'item_buyers' => post_or_db('item_buyers', false),
        'raid_id' => post_or_db('raid_id', false),
        'item_value' => post_or_db('item_value', false)
    );
}

//
// Processing
//
switch ( $action )
{
    //
    // Add
    //
    case 'add':
        $item_name = ( !empty($_POST['item_name']) ) ? $_POST['item_name'] : $_POST['select_item_name'];
        $item_date = $db->query_first('SELECT raid_date FROM ' . RAIDS_TABLE . " WHERE raid_id='".$_POST['raid_id']."'");

        $item_group_key = generate_item_group_key($item_name, $item_date, $_POST['raid_id']);

        foreach ( $_POST['item_buyers'] as $k => $v )
        {
            $sql = 'UPDATE ' . MEMBERS_TABLE . '
                    SET member_spent = member_spent+'.$_POST['item_value']."
                    WHERE member_name='".$v."'";
            $db->query($sql);

            $sql = 'INSERT INTO ' . ITEMS_TABLE . "
                    (item_id, item_name, item_buyer, raid_id, item_value, item_date, item_group_key, item_added_by)
                    VALUES
                    ('NULL','".remove_quote_escape($item_name)."','".$v."','".$_POST['raid_id']."','".$_POST['item_value']."','".$item_date."','".$item_group_key."','".$item_added_by."')";
            $db->query($sql);
        }

        $item_buyers = implode(', ', $_POST['item_buyers']);
        $log_action = array(
            'header' => '{L_ACTION_ITEM_ADDED}',
            '{L_NAME}' => $item_name,
            '{L_BUYERS}' => $item_buyers,
            '{L_RAID_ID}' => $_POST['raid_id'],
            '{L_VALUE}' => $_POST['item_value'],
            '{L_ADDED_BY}' => $item_added_by);
        $eqdkp->log_insert(array(
            'log_type' => $log_action['header'],
            'log_action' => $eqdkp->make_log_action($log_action),
            'log_ipaddress' => $user->ip,
            'log_sid' => $user->session_id,
            'log_result' => '{L_SUCCESS}',
            'admin_id' => $user->data['user_id'])
        );

        $success_message = sprintf($user->lang['admin_add_item_success'], $item_name, $item_buyers, $_POST['item_value']);
        $link_list = generate_admin_success_links(array(
            $user->lang['add_item'] => 'additem.php'.$SID,
            $user->lang['list_items'] => 'listitems.php'.$SID)
        );

        message_die(stripslashes($success_message) . '<br /><br />' . $link_list);

        break;
    //
    // Update
    //
    case 'update':
        // Remove the charge of each item from the previous buyers
        $sql = 'SELECT i2.*
                FROM ( ' . ITEMS_TABLE . ' i1
                LEFT JOIN ' . ITEMS_TABLE . " i2
                ON i1.item_group_key = i2.item_group_key )
                WHERE i1.item_id='".$item_id."'";
        $result = $db->query($sql);
        $old_buyers = array();
        while ( $row = $db->fetch_record($result) )
        {
            $db->query('DELETE FROM ' . ITEMS_TABLE . " WHERE item_id='".$row['item_id']."'");
            $db->query('UPDATE ' . MEMBERS_TABLE . " SET member_spent = member_spent-".$row['item_value']." WHERE member_name='".$row['item_buyer']."'");

            $old_buyers[] = addslashes($row['item_buyer']);

            $old_item = array(
                'item_name' => addslashes($row['item_name']),
                'item_buyers' => $old_buyers,
                'raid_id' => addslashes($row['raid_id']),
                'item_date' => addslashes($row['item_date']),
                'item_value' => addslashes($row['item_value']));
        }

        $item_name = ( !empty($_POST['item_name']) ) ? $_POST['item_name'] : $_POST['select_item_name'];
        $item_date = $db->query_first('SELECT raid_date FROM ' . RAIDS_TABLE . " WHERE raid_id='".$_POST['raid_id']."'");

        $item_group_key = generate_item_group_key($item_name, $item_date, $_POST['raid_id']);

        // All 'old' items with this group key are gone
        // Add new rows for new items, with new group keys and (maybe) new buyers
        foreach ( $_POST['item_buyers'] as $k => $v )
        {
            $sql = 'UPDATE ' . MEMBERS_TABLE . '
                    SET member_spent = member_spent+'.$_POST['item_value']."
                    WHERE member_name='".$v."'";
            $db->query($sql);

            $sql = 'INSERT INTO ' . ITEMS_TABLE . "
                    (item_id, item_name, item_buyer, raid_id, item_value, item_date, item_group_key, item_added_by)
                    VALUES
                    ('NULL','".remove_quote_escape($item_name)."','".$v."','".$_POST['raid_id']."','".$_POST['item_value']."','".$item_date."','".$item_group_key."','".$item_added_by."')";
            $db->query($sql);
        }

        $item_buyers = implode(', ', $_POST['item_buyers']);
        $log_action = array(
            'header' => '{L_ACTION_ITEM_UPDATED}',
            '{L_NAME_BEFORE}' => $old_item['item_name'],
            '{L_BUYERS_BEFORE}' => implode(', ', $old_item['item_buyers']),
            '{L_RAID_ID_BEFORE}' => $old_item['raid_id'],
            '{L_VALUE_BEFORE}' => $old_item['item_value'],
            '{L_NAME_AFTER}' => find_difference($old_item['item_name'], $item_name),
            '{L_BUYERS_AFTER}' => implode(', ', find_difference($old_item['item_buyers'], $_POST['item_buyers'])),
            '{L_RAID_ID_AFTER}' => find_difference($old_item['raid_id'], $_POST['raid_id']),
            '{L_VALUE_AFTER}' => find_difference($old_item['item_value'], $_POST['item_value']),
            '{L_UPDATED_BY}' => $item_updated_by);
        $eqdkp->log_insert(array(
            'log_type' => $log_action['header'],
            'log_action' => $eqdkp->make_log_action($log_action),
            'log_ipaddress' => $user->ip,
            'log_sid' => $user->session_id,
            'log_result' => '{L_SUCCESS}',
            'admin_id' => $user->data['user_id'])
        );

        $success_message = sprintf($user->lang['admin_update_item_success'], $old_item['item_name'], implode(', ', $old_item['item_buyers']), $old_item['item_value']);
        $link_list = generate_admin_success_links(array(
            $user->lang['add_item'] => 'additem.php'.$SID,
            $user->lang['list_items'] => 'listitems.php'.$SID)
        );

        message_die(stripslashes($success_message) . '<br /><br />' . $link_list);

        break;
    //
    // Delete
    //
    case 'delete':
        if ( !$confirm )
        {
            confirm_delete($user->lang['confirm_delete_item'], URI_ITEM, $item_id, 'additem.php'.$SID);
        }
        else
        {
            // Remove the charge of each item from the previous buyers
            $sql = 'SELECT i2.*
                    FROM ( ' . ITEMS_TABLE . ' i1
                    LEFT JOIN ' . ITEMS_TABLE . " i2
                    ON i1.item_group_key = i2.item_group_key )
                    WHERE i1.item_id='".$item_id."'";
            $result = $db->query($sql);
            $old_buyers = array();
            while ( $row = $db->fetch_record($result) )
            {
                $db->query('DELETE FROM ' . ITEMS_TABLE . " WHERE item_id='".$row['item_id']."'");
                $db->query('UPDATE ' . MEMBERS_TABLE . " SET member_spent = member_spent-".$row['item_value']." WHERE member_name='".$row['item_buyer']."'");

                $old_buyers[] = addslashes($row['item_buyer']);

                $old_item = array(
                    'item_name' => addslashes($row['item_name']),
                    'item_buyers' => $old_buyers,
                    'raid_id' => addslashes($row['raid_id']),
                    'item_date' => addslashes($row['item_date']),
                    'item_value' => addslashes($row['item_value']));
            }

            $item_buyers = implode(', ', $old_item['item_buyers']);
            $log_action = array(
                'header' => '{L_ACTION_ITEM_DELETED}',
                '{L_NAME}' => $old_item['item_name'],
                '{L_BUYERS}' => $item_buyers,
                '{L_RAID_ID}' => $old_item['raid_id'],
                '{L_VALUE}' => $old_item['item_value']);
            $eqdkp->log_insert(array(
                'log_type' => $log_action['header'],
                'log_action' => $eqdkp->make_log_action($log_action),
                'log_ipaddress' => $user->ip,
                'log_sid' => $user->session_id,
                'log_result' => '{L_SUCCESS}',
                'admin_id' => $user->data['user_id'])
            );

            $success_message = sprintf($user->lang['admin_delete_item_success'], $old_item['item_name'], $item_buyers, $old_item['item_value']);
            $link_list = generate_admin_success_links(array(
                $user->lang['add_item'] => 'additem.php'.$SID,
                $user->lang['list_items'] => 'listitems.php'.$SID)
            );

            message_die(stripslashes($success_message) . '<br /><br />' . $link_list);
        } // confirmed
        break;
    //
    // Display form
    //
    case 'display':
        $show_all = ( (!empty($_GET['show'])) && ($_GET['show'] == 'all') ) ? true : false;

        // Member names drop-down
        $members_result = $db->query('SELECT member_name FROM ' . MEMBERS_TABLE . ' ORDER BY member_name');
        while ( $row = $db->fetch_record($members_result) )
        {
            if ( $item_id )
            {
                $selected = ( @in_array($row['member_name'], $item['item_buyers']) ) ? ' selected="selected"' : '';
            }
            else
            {
                $selected = ( @in_array($row['member_name'], $_POST['item_buyers']) ) ? ' selected="selected"' : '';
            }

            $tpl->assign_block_vars('members_row', array(
                'VALUE' => $row['member_name'],
                'SELECTED' => $selected,
                'OPTION' => $row['member_name'])
            );
        }
        $db->free_result($members_result);

        // Raids drop-down
        // Make two_weeks two weeks before the date the item was purchased
        $two_weeks = mktime(0, 0, 0, date('m', $item_date), date('d', $item_date)-14, date('y', $item_date));

        $sql_where_clause = ( $show_all ) ? '' : ' WHERE (raid_date >= '.$two_weeks.')';
        $sql = 'SELECT raid_id, raid_name, raid_date
                FROM ' . RAIDS_TABLE .
                $sql_where_clause . '
                ORDER BY raid_date DESC';
        $raids_result = $db->query($sql);
        $raid_id = ( isset($_GET['raid_id']) ) ? $_GET['raid_id'] : '0'; // 'Add items from this raid' link
        while ( $row = $db->fetch_record($raids_result) )
        {
            $tpl->assign_block_vars('raids_row', array(
                'VALUE' => $row['raid_id'],
                'SELECTED' => ( ($raid_id == $row['raid_id']) || ($item['raid_id'] == $row['raid_id']) ) ? ' selected="selected"' : '',
                'OPTION' => date($user->style['date_notime_short'], $row['raid_date']) . ' - ' . stripslashes($row['raid_name']))
            );
        }
        $db->free_result($raids_result);

        // Item drop-down
        $max_value = $db->query_first('SELECT max(item_value) FROM ' . ITEMS_TABLE);
        $float = @explode('.', $max_value);
        $format = '%0' . @strlen($float[0]) . '.2f';
        
        $previous_item = '';
        $sql = 'SELECT item_value, item_name
                FROM ' . ITEMS_TABLE . '
                ORDER BY item_name, item_date DESC';
        $items_result = $db->query($sql);
        while ( $row = $db->fetch_record($items_result) )
        {
            $item_select_name = stripslashes(trim($row['item_name']));
            $item_name = stripslashes(trim($item['item_name']));
            
            if ( $previous_item != $item_select_name )
            {
                $tpl->assign_block_vars('items_row', array(
                    'VALUE' => $item_select_name,
                    'SELECTED' => ( ($item_select_name == $item_name) || ($item_select_name == $item['select_item_name']) ) ? ' selected="selected"' : '',
                    'OPTION' => '('.sprintf($format, $row['item_value']).') - '.$item_select_name)
                );
                
                $previous_item = $item_select_name;
            }
        }
        $db->free_result($items_result);

        $tpl->assign_vars(array(
            'F_ADD_ITEM' => 'additem.php'.$SID,
            'ITEM_ID' => $item_id,
            
            'U_ADD_RAID' => 'addraid.php'.$SID,

            'ITEM_NAME' => stripslashes($item['item_name']),
            'ITEM_VALUE' => $item['item_value'],

            'L_ADD_ITEM_TITLE' => $user->lang['additem_title'],
            'L_BUYERS' => $user->lang['buyers'],
            'L_HOLD_CTRL_NOTE' => '('.$user->lang['hold_ctrl_note'].')<br />',
            'L_RAID' => $user->lang['raid'],
            'L_ADD_RAID' => strtolower($user->lang['add_raid']),
            'L_NOTE' => $user->lang['note'],
            'L_ADDITEM_RAIDID_NOTE' => ( !$show_all ) ? sprintf($user->lang['additem_raidid_note'], '<a href="additem.php'.$SID.'&amp;show=all'.( ( $item_id ) ? '&amp;' . URI_ITEM . '='.$item_id : '').'">') : $user->lang['additem_raidid_showall_note'],
            'L_ITEM' => $user->lang['item'],
            'L_SELECT_EXISTING' => $user->lang['select_existing'],
            'L_OR' => strtolower($user->lang['or']),
            'L_ENTER_NEW' => $user->lang['enter_new'],
            'L_VALUE' => $user->lang['value'],
            'L_ADD_ITEM' => $user->lang['add_item'],
            'L_RESET' => $user->lang['reset'],
            'L_UPDATE_ITEM' => $user->lang['update_item'],
            'L_DELETE_ITEM' => $user->lang['delete_item'],

            'FV_ITEM_BUYERS' => $fv->generate_error('item_buyers'),
            'FV_RAID_ID' => $fv->generate_error('raid_id'),
            'FV_ITEM_NAME' => $fv->generate_error('item_name'),
            'FV_ITEM_VALUE' => $fv->generate_error('item_value'),

            'MSG_NAME_EMPTY' => $user->lang['fv_required_item_name'],
            'MSG_RAID_ID_EMPTY' => $user->lang['fv_required_raidid'],
            'MSG_VALUE_EMPTY' => $user->lang['fv_required_value'],
            'ITEM_VALUE_LENGTH' => @strlen($float[0])+3, // The first two digits plus '.00';

            'S_MULTIPLE_BUYERS' => ( !$item_id ) ? true : false,
            'S_ADD' => ( !$item_id ) ? true : false)
        );

        $page_title = sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['additem_title'];
        include_once($eqdkp_root_path . 'includes/page_header.php');
        
        $tpl->set_filenames(array(
            'body' => 'admin/additem.html')
        );
        
        include_once($eqdkp_root_path . 'includes/page_tail.php');
        break;
}

/**
* Generate our 32-character group key
* This allows us to see who else looted this item, from this raid on this date
* (basically who else was selected as a 'buyer' for this submit) even though
* the buyers are entered into their own rows
*
* @param $item_name
* @param $item_date
* @param $raid_id
* @return string Item Group Key
*/
function generate_item_group_key($item_name, $item_date, $raid_id)
{
    $hash_item_name = htmlspecialchars(stripslashes($item_name));

    $raid_id_part = substr(md5($raid_id), 0, 10);
    $item_name_part = substr(md5($hash_item_name), 0, 11);
    $item_date_part = substr(md5($item_date), 0, 11);

    $item_group_key = $raid_id_part . $item_name_part . $item_date_part;

    return md5(uniqid($item_group_key));
}
?>